import React, {Component} from 'react';
import {
	Dimensions,
	Platform,
	NativeModules,
	DeviceInfo,
	StyleSheet,
	Image,
	Text,
	View,
	TextInput,
	PixelRatio,
	TouchableOpacity,
	AsyncStorage,
	ScrollView
} from 'react-native';

var Common = require('./common');
import moment from 'moment';
// iPhoneX
const X_WIDTH = 375;
const X_HEIGHT = 812;

// screen
const SCREEN_WIDTH = Dimensions.get('window').width;
const SCREEN_HEIGHT = Dimensions.get('window').height;

const pixelRatio = PixelRatio.get();
const dismissKeyboard = require('dismissKeyboard');
export default class HudongDetail extends Component<Props> {
	constructor(props) {
		super(props);
		this.state = {
			iphonex: false,
			showCeng: false,
			str: '推荐',
			news: {},
			imgsrc: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1514356844477&di=7c57fde0860194258cbec5c2720e0cf5&imgtype=0&src=http%3A%2F%2Fwww.swkweike.com%2Fdata%2Fuploads%2F2015%2F05%2F26%2F20430804665564348adc669.png',
			zanCount: 0,
			zanPicData: [],
			isZan: false,//是否点过赞
			isShoucang: false,//是否收藏过
			pinglun: [],//评论的数据
		};
	}

	static navigationOptions = {
		tabBarLabel: '资讯',
		tabBarIcon: ({focused}) => {
			if (focused) {
				return (
					<Image style={[styles.bnavImg, {width: 22, height: 22}]} source={require('./images/zixun1.png')}/>
				);
			}
			return (
				<Image style={[styles.bnavImg, {width: 22, height: 22}]} source={require('./images/zixun.png')}/>
			);
		},
	};

	isIphoneX() {

		return (

			Platform.OS === 'ios' &&

			((SCREEN_HEIGHT === X_HEIGHT && SCREEN_WIDTH === X_WIDTH) ||

				(SCREEN_HEIGHT === X_WIDTH && SCREEN_WIDTH === X_HEIGHT))

		)

	}


	ifIphoneX() {
		var flag = this.isIphoneX();
		if (flag) {
			console.log('true')
			this.setState({
				iphonex: true
			})
		} else {
			console.log('false')
			this.setState({
				iphonex: false
			})
		}
	}


	login() {
		var _this = this;
		Common.ajaxPost(Common.url + 'login.php', function (res) {
			if (res.code == "0000") {

			}
		}.bind(this), {verify: '08login', t: ''});
	}

	toRegister() {
		this.props.navigation.navigate('Register')
	}

	toHomeBack() {

		this.props.navigation.goBack()
	}

	changeTabs(str) {
		this.setState({
			str: str
		})
	}

	toSendWords() {
		this.props.navigation.navigate('SendWords')
	}

	toSendVideo() {
		this.props.navigation.navigate('SendVideo')
	}

	showCeng() {
		this.setState({
			showCeng: true,
		})
	}

	hideCeng() {
		this.setState({
			showCeng: false,
		})
	}

	getData() {
		var _this = this;

		Common.ajaxGet(Common.url + 'article.php?action=detail&id=' + this.state.id, function (res) {
			console.log(res)
			if (res.code == 1) {
				var data = res.data;
				this.setState({
					news: data,
				})
			}
		}.bind(this), {verify: '08login', t: ''});
	}

	renderPic(pic) {
		return pic.map(function (data, index) {
			return (
				<Image key={index} style={styles.imgsItem} source={{uri: data.attach_url}}/>
			);
		})
	}

	//收藏
	shoucang() {

		var _this = this;
		var suburl = '';
		if (this.state.isShoucang) {
			suburl = 'thinksns/index.php?app=widget&mod=Collection&act=delColl&is_ajax=1'
		} else {
			suburl = 'thinksns/index.php?app=widget&mod=Collection&act=addColl&is_ajax=1'
		}
		var config = {
			method: 'POST',
			headers: {
				'Accept': 'application/json',
				'Content-Type': 'application/json',
				'credentials': 'include',
				'Cookie': _this.state.cookie
			},
			credentials: 'include'
		}
		var param = {
			"sid": _this.state.news.feed_id,
			"stable": 'feed'
		}
		if (!this.state.isShoucang) {
			param.sapp = 'public'
		}
		console.log(param)
		console.log(suburl)
		if (param) {
			config["body"] = JSON.stringify(param);
		}
		fetch(Common.url + suburl, config).then((response) => response.json()).then((res) => {
			console.log(res)
			if (res.status == 1) {
				this.setState({
					isShoucang: !this.state.isShoucang
				})
			} else {
				if (res.info == "未登录") {
					this.props.navigation.navigate('Login')
				}
				else if(res.status == 401){
					this.props.navigation.navigate('Login')
				}
			}
		})

	}


	//点赞
	zan() {///thinksns/index.php?app=widget&mod=Digg&act=addDigg
		//thinksns/index.php?app=widget&mod=Digg&act=delDigg  --取消
		var _this = this;
		var suburl = '';
		if (this.state.isZan) {
			suburl = 'thinksns/index.php?app=widget&mod=Digg&act=delDigg';
		} else {
			suburl = 'thinksns/index.php?app=widget&mod=Digg&act=addDigg'
		}
		var config = {
			method: 'POST',
			headers: {
				'Accept': 'application/json',
				'Content-Type': 'application/json',
				'credentials': 'include',
				'Cookie': _this.state.cookie
			},
			credentials: 'include'
		}
		var param = {
			"feed_id": _this.state.news.feed_id,
		}
		if (param) {
			config["body"] = JSON.stringify(param);
		}
		fetch(Common.url + suburl, config).then((response) => response.json()).then((res) => {
			console.log(res)
			if (res.status == 1) {
				this.setState({
					isZan: !this.state.isZan
				}, () => {
					var zanCount = parseInt(this.state.zanCount);
					if (this.state.isZan) {
						zanCount += 1;
						this.setState({
							zanCount: zanCount
						})
					} else {
						zanCount -= 1;
						this.setState({
							zanCount: zanCount
						})
					}
				})
			} else {
				if (res.info == "未登录") {
					this.props.navigation.navigate('Login')
				}
			}
		})
	}

	getZan() {
		var _this = this;

		var config = {
			method: 'POST',
			headers: {
				'Accept': 'application/json',
				'Content-Type': 'application/json',
				'credentials': 'include',
				'Cookie': _this.state.cookie
			},
			credentials: 'include'
		}
		var param = {
			"feed_id": _this.state.news.feed_id,
			"is_ajax": 1
		}
		if (param) {
			config["body"] = JSON.stringify(param);
		}

		fetch(Common.url + 'thinksns/index.php?app=widget&mod=Digg&act=digglist', config).then((response) => response.json()).then((res) => {
			console.log(res)
			if (res.status == 1) {
				this.setState({
					zanCount: parseInt(res.info.count)
				})
				if (res.info.data && res.info.data.length) {
					this.setState({
						zanPicData: res.info.data
					})
				}
			}
		})
	}

	//点赞人的头像
	renderZanPic(pic) {
		return pic.map(function (data, index) {
			return (
				<Image key={index} style={{width: 31, height: 31, marginRight: 8, borderRadius: 16,}}
				       source={{uri: data.feed.avatar_middle}}/>
			);
		})
	}

	getComment() {
		var _this = this;

		var config = {
			method: 'POST',
			headers: {
				'Accept': 'application/json',
				'Content-Type': 'application/json',
				'credentials': 'include',
				'Cookie': _this.state.cookie
			},
			credentials: 'include'
		}
		var param = {
			"app_name": "public",
			"table": "feed",
			"row_id": _this.state.news.feed_id,
			"cancomment": 1,

		}
		if (param) {
			config["body"] = JSON.stringify(param);
		}
		fetch(Common.url + 'thinksns/index.php?app=widget&mod=Comment&act=getCommentList&is_ajax=1', config).then((response) => response.json()).then((res) => {
			console.log(res)
			if (res.status == 1) {
				if (res.data && res.data.list && res.data.list.datainfo && res.data.list.datainfo.length) {
					var data = res.data.list.datainfo;
					for (var item of data) {
						item.time = moment(parseFloat(item.ctime + '000')).format('YYYY-MM-DD HH:mm:ss');
					}
					this.setState({
						pinglun: data
					})
				}
			}
		})
	}

	renderpinglun(news) {
		var _this = this;
		var bgColor = '#fff';
		return news.map(function (data, index) {
			return (
				<View key={index} style={styles.pinglunItem}>
					<View style={styles.itemTop}>
						<Image style={{width: 32, height: 32, marginRight: 10, borderRadius: 16,}}
						       source={{uri: data.user_info.avatar_original}}/>
						<View style={{flex: 1}}>
							<Text style={{fontSize: 16,}}>{data.user_info.uname}</Text>
							<View style={{flexDirection: 'row', alignItems: 'center',}}>
								<Text style={{fontSize: 14, color: '#666'}}>{data.time}</Text>
								{/*
                  <View style={{flexDirection:'row',alignItems:'center',justifyContent:'flex-end',flex:1}}>
                    <Image style={{width:22,height:22,marginLeft:20}} source={require('./images/pinglun-erji.png')} />
                    <Image style={{width:22,height:22}} source={require('./images/pinglundianzaqn.png')} />
                    <Text style={{fontSize:14,color:'#b2b2b2'}}>8</Text>
                  </View>
                  */}
							</View>
						</View>
					</View>
					<Text
						style={{fontSize: 16, marginLeft: 42, paddingTop: 10, paddingBottom: 10,}}>{data.content}</Text>
					{/*<View style={styles.replay}>
              <View style={{flexDirection:'row',paddingBottom:10,}}>
                <Text style={{fontSize:14,color:'#4868e0'}}>nickname</Text>
                <Text style={{fontSize:14,color:'#464646'}}>：内容内容内容内容</Text>
              </View>
            </View>*/}
				</View>
			);
		})
	}

	//评论接口 http://118.123.13.251:8012/thinksns/index.php?app=widget&mod=Comment&act=addcomment&is_ajax=1
	writeComment() {
		var _this = this;
		if (!this.state.text) {
			return;
		}
		var config = {
			method: 'POST',
			headers: {
				'Accept': 'application/json',
				'Content-Type': 'application/json',
				'credentials': 'include',
				'Cookie': _this.state.cookie
			},
			credentials: 'include'
		}
		var param = {
			app_name: 'public',
			table_name: 'feed',
			app_uid: 0,
			row_id: _this.state.news.feed_id,
			to_comment_id: 0,
			to_uid: 0,//回复人id(默认0)
			app_row_id: 0,
			app_row_table: 'feed',
			content: _this.state.text,
			ifShareFeed: 0,
			comment_old: 0,
			app_detail_url: '',
			http: '',//118.123.13.251:8012/thinksns/index.php?app=public&mod=Index&act=index
			talkbox: 0

		}
		if (param) {
			config["body"] = JSON.stringify(param);
		}
		fetch(Common.url + 'thinksns/index.php?app=widget&mod=Comment&act=addcomment&is_ajax=1', config).then((response) => response.json()).then((res) => {
			console.log(res)
			if (res.status == 1) {
				_this.setState({
					pinglun: []
				}, () => {
					this.getComment();
				})
			}
		})
	}

	componentWillMount() {
		AsyncStorage.getItem('cookie').then((value) => {
			console.log(value)
			this.setState({
				cookie: value
			})
		})
		console.log(this.props.navigation.state.params)
		this.setState({
			news: this.props.navigation.state.params
		}, () => {
			var feed_id = parseFloat(this.state.news.feed_id)
			if (this.state.news.diggArr && this.state.news.diggArr[feed_id]) {
				console.log('zan')
				this.setState({
					isZan: true
				})
			} else {
				console.log('meizan')
				this.setState({
					isZan: false
				})
			}
			if (this.state.news.collectArr && this.state.news.collectArr[feed_id]) {
				this.setState({
					isShoucang: true
				})
			} else {
				this.setState({
					isShoucang: false
				})
			}
			this.getZan();
			this.getComment();
		})
		this.ifIphoneX();
		// console.log(this.props.navigation.state.params)
		// if(this.props.navigation.state.params.from){
		//   this.setState({
		//     from:this.props.navigation.state.params,
		//   })
		// }
	}

	render() {
		return (
			<View style={styles.container}>
				<View style={styles.head}>
					<TouchableOpacity style={styles.toback} onPress={this.toHomeBack.bind(this)}>
						<Text style={{fontSize: 16,}}>返回</Text>
					</TouchableOpacity>
					<Text style={styles.headTitle}>详情</Text>
				</View>
				<View style={{padding: 15, backgroundColor: '#fff'}}>
					<View style={styles.user}>
						<Image style={{width: 36, height: 36, borderRadius: 18}}
						       source={{uri: this.state.news.user_info.avatar_original}}/>
						<View style={{paddingLeft: 10,}}>
							<Text style={styles.userText}>{this.state.news.user_info.uname}</Text>
							<Text style={{fontSize: 14, color: '#8c8c8c'}}>{this.state.news.publish_time}</Text>
						</View>
					</View>
					<Text style={styles.textContent}>{this.state.news.content_txt}</Text>
					<View style={styles.imgs}>
						{this.state.news.var && this.state.news.var.attachInfo && this.state.news.var.attachInfo.length ? (
							this.renderPic(this.state.news.var.attachInfo)
						) : (null)}
					</View>
					<View style={styles.btns}>
						<TouchableOpacity style={styles.btnItem} onPress={this.zan.bind(this)}>
							{!this.state.isZan ? (
								<Image style={{width: 22, height: 22, marginRight: 6}}
								       source={require('./images/zan.png')}/>
							) : (
								<Image style={{width: 22, height: 22, marginRight: 6}}
								       source={require('./images/yizan.png')}/>
							)}

							<Text style={{color: '#363636', fontSize: 14}}>赞</Text>
						</TouchableOpacity>
						<TouchableOpacity style={styles.btnItem}>
							<Image style={{width: 22, height: 22, marginRight: 6}}
							       source={require('./images/pinglun.png')}/>
							<Text style={{color: '#363636', fontSize: 14}}>评论</Text>
						</TouchableOpacity>
						<TouchableOpacity style={styles.btnItem} onPress={this.shoucang.bind(this)}>
							{!this.state.isShoucang ? (
								<Image style={{width: 22, height: 22, marginRight: 6}}
								       source={require('./images/shoucang.png')}/>
							) : (
								<Image style={{width: 22, height: 22, marginRight: 6}}
								       source={require('./images/yishoucang.png')}/>
							)}
							<Text style={{color: '#363636', fontSize: 14}}>收藏</Text>
						</TouchableOpacity>
					</View>
				</View>
				<View style={{height: 5, backgroundColor: '#f5f5f5'}}></View>
				<View style={styles.hudongBottom}>
					<View style={styles.pinlunTop}>
						<Image style={{width: 14, height: 14, marginRight: 22}}
						       source={require('./images/erjiyeyizan.png')}/>
						<View style={styles.headpic}>
							{this.state.zanPicData.length ? (
								this.renderZanPic(this.state.zanPicData)
							) : (null)}
						</View>
						<View style={styles.totalzan}>
							<Text style={{fontSize: 14, color: '#888'}}>{this.state.zanCount}个赞</Text>
							<Image style={{width: 22, height: 22,}} source={require('./images/jiantou.png')}/>
						</View>
					</View>
					<View style={{paddingTop: 10}}>
						<Image style={{width: 22, height: 22, marginLeft: 20}}
						       source={require('./images/pinglun.png')}/>
						<ScrollView style={{paddingBottom: 45}}>
							{this.state.pinglun.length ? (
								this.renderpinglun(this.state.pinglun)
							) : (null)}
						</ScrollView>
					</View>
				</View>
				<View style={{height: 51}}></View>
				<View style={styles.topinglun}>
					<TextInput
						style={{flex: 1, padding: 10,}}
						multiline={true}
						onChangeText={(text) => this.setState({text})}
						value={this.state.text}
						placeholder='发表评论...'
						placeholderTextColor='#4868e0'
					/>
					<TouchableOpacity onPress={this.writeComment.bind(this)}>
						<Text style={styles.btnpinglun}>评论</Text>
					</TouchableOpacity>
				</View>
			</View>
		);
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		height: Common.screenHeight,
		backgroundColor: '#fff',
	},
	head: {
		height: 50,
		width: Common.screenWidth,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',
		backgroundColor: '#fff',
		borderBottomColor: '#dbdbdb',
		borderBottomWidth: 1,
	},
	headTitle: {
		fontSize: 16,
	},
	toback: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',
		height: 50,
		position: 'absolute',
		left: 20,
		top: 0,
		fontSize: 14,
	},
	user: {
		flexDirection: 'row',
		alignItems: 'center',
	},
	userText: {
		fontSize: 16
	},
	textContent: {
		fontSize: 16,
		lineHeight: 20,
		marginTop: 10,
	},
	imgs: {
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		paddingTop: 10,
		paddingBottom: 13,
	},
	imgsItem: {
		width: (Common.screenWidth - 70) / 3,
		height: (Common.screenWidth - 70) / 3,
		marginLeft: 5,
		marginRight: 5
	},
	btns: {
		flexDirection: 'row',
		alignItems: 'center',
	},
	btnItem: {
		width: 70,
		height: 28,
		marginRight: 10,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',
		borderColor: '#ebebeb',
		borderWidth: 1,
		borderRadius: 4,
	},
	hudongBottom: {
		backgroundColor: '#fff',
	},
	pinlunTop: {
		flexDirection: 'row',
		alignItems: 'center',
		paddingBottom: 8,
		paddingTop: 8,
		paddingLeft: 15,
		paddingRight: 15,
		borderBottomColor: '#f0f0f0',
		borderBottomWidth: 1,
	},
	headpic: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',

	},
	totalzan: {
		flex: 1,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'flex-end',
	},
	pinglunItem: {
		padding: 15,
		borderBottomColor: '#f0f0f0',
		borderBottomWidth: 1,
	},
	itemTop: {
		flexDirection: 'row',
		alignItems: 'center',
	},
	replay: {
		backgroundColor: '#f1f1f1',
		paddingLeft: 10,
		paddingRight: 10,
		paddingTop: 10,
	},
	topinglun: {
		width: Common.screenWidth,
		position: 'absolute',
		left: 0,
		bottom: 0,
		paddingLeft: 15,
		paddingRight: 15,
		paddingBottom: 5,
		flexDirection: 'row',
		alignItems: 'center',
		backgroundColor: '#fafafa',
		borderRadius: 4,
		borderColor: '#ebebeb',
		borderWidth: 1,
	},
	btnpinglun: {
		backgroundColor: '#4868e0',
		color: '#fff',
		paddingLeft: 5,
		paddingRight: 5,
		paddingTop: 3,
		paddingBottom: 3,
		borderRadius: 4,
	},


	bnav: {
		width: Common.screenWidth,
		height: 50,
		position: 'absolute',
		left: 0,
		bottom: 0,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',
		backgroundColor: '#f4f5f8',
		borderTopColor: '#afafaf',
		borderTopWidth: 1,
	},
	bnavItem: {
		flex: 1,
		flexDirection: 'column',
		alignItems: 'center',
		justifyContent: 'center'
	},
	bnavText: {
		textAlign: 'center',
		paddingTop: 5,
	},
	bnavImg: {
		margin: 'auto'
	}
});
